package com.it.nongchanping.controller;

import com.it.nongchanping.entity.Product;
import com.it.nongchanping.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/product")
public class AdminProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("")
    public String list(Model model) {
        List<Product> products = productService.getAllProducts();
        model.addAttribute("products", products);
        model.addAttribute("title", "产品管理");
        model.addAttribute("activePage", "product");
        return "admin/product/list";
    }

    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("product", new Product());
        model.addAttribute("title", "添加新产品");
        model.addAttribute("activePage", "product");
        return "admin/product/form";
    }

    @PostMapping("/save")
    public String saveProduct(@ModelAttribute Product product, RedirectAttributes redirectAttributes) {
        boolean success;
        if (product.getId() == null) {
            success = productService.saveProduct(product);
        } else {
            success = productService.updateProduct(product);
        }
        
        if (success) {
            redirectAttributes.addFlashAttribute("message", "产品保存成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "产品保存失败！");
        }
        return "redirect:/admin/product";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model) {
        Product product = productService.getProductById(id);
        model.addAttribute("product", product);
        model.addAttribute("title", "编辑产品");
        model.addAttribute("activePage", "product");
        return "admin/product/form";
    }

    @GetMapping("/delete/{id}")
    public String deleteProduct(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        if (productService.deleteProduct(id)) {
            redirectAttributes.addFlashAttribute("message", "产品删除成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "产品删除失败！");
        }
        return "redirect:/admin/product";
    }
} 